const crypto = require('crypto');
const getHashValue = (value, salt = '') => {
    // 生成一个随机的盐值
    if (!salt) {
        salt = crypto.randomBytes(16).toString('hex');
    }
    // 把盐值添加到密码中，然后进行哈希
    const hashValue = crypto.pbkdf2Sync(value, salt, 1000, 64, 'sha512').toString('hex');
    const saltedHash = salt + ":" + hashValue;
    return saltedHash
}

const { body, validationResult } = require('express-validator');
// 封装验证函数
const validateFields = (fields) => {
    const validators = [];
    fields.forEach(({ field, noEmpty, validType, errorMessage }) => {
        let validator = body(field);
        if (noEmpty) {
            validator = validator.notEmpty().withMessage(errorMessage || `${field} must not be empty`);
        }
        // 可以为空并且数据为空
        if(!noEmpty&&validator.isEmpty()){
        }
        else if (validType === 'string') {
            validator = validator.isString().withMessage(errorMessage || `${field} must be a string`);
        } else if (validType === 'int') {
            validator = validator.isInt().withMessage(errorMessage || `${field} must be an integer`);
        } else if (validType === 'boolean') {
            validator = validator.isBoolean().withMessage(errorMessage || `${field} must be a boolean`);
        } else if (validType === 'email') {
            validator = validator.isEmail().withMessage(errorMessage || `${field} must be a valid email`);
        }
        validators.push(validator);
    });

    validators.push((req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    });

    return validators;
}
module.exports = { getHashValue, validateFields }